﻿/**
 * Copyright (C) 2012 - present by Privosoft LLC. 
 * 
 * Please see distribution for license.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net.Appender;
using log4net;
using log4net.Layout;
using log4net.Repository.Hierarchy;
using log4net.Core;

namespace Privosoft.DataFrame
{

    public class Logger
    {
        private PatternLayout _layout = new PatternLayout();
        private const string LOG_PATTERN = "%d [%t] %-5p %m%n";

        public string DefaultPattern
        {
            get { return LOG_PATTERN; }
        }

        public Logger()
        {
            _layout.ConversionPattern = DefaultPattern;
            _layout.ActivateOptions();
        }

        public PatternLayout DefaultLayout
        {
            get { return _layout; }
        }

        public void AddAppender(IAppender appender)
        {
            Hierarchy hierarchy =
                    (Hierarchy)LogManager.GetRepository();

            hierarchy.Root.AddAppender(appender);
        }

        private static ILog InitLogger(string pathToFile)
        {
            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
            TraceAppender tracer = new TraceAppender();
            PatternLayout patternLayout = new PatternLayout();

            patternLayout.ConversionPattern = LOG_PATTERN;
            patternLayout.ActivateOptions();

            tracer.Layout = patternLayout;
            tracer.ActivateOptions();
            hierarchy.Root.AddAppender(tracer);
            var appender = new FileAppender();
            
            appender.Layout = patternLayout;
            appender.AppendToFile = false;
            appender.File = pathToFile;
            appender.Name = "file";
            appender.ActivateOptions();
            hierarchy.Root.AddAppender(appender);

            hierarchy.Root.Level = Level.All;
            hierarchy.Configured = true;

            return LogManager.GetLogger("file");
        }

        private static ILog _instance;
        public static ILog Create(string pathToFile)
        {
            if (_instance == null) _instance = InitLogger(pathToFile);
            return _instance;
        }

        public static void Log(LogLevels level, int row, string message, Privosoft.DataFrame.Column column)
        {
            string s = String.Format("{0},{1},\"{2}\",\"{3}\"", new Object[] { level.ToString(), row, message, column == null ? "" : column.Name });
            if (_instance == null)
            {
                Console.WriteLine(s);
            }
            else
            {
                _instance.Info(s);
            }
        }
    }
}
